package com.maodou.core.datastore.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.maodou.core.datastore.db.table.CacheEntry

@Dao
interface CacheDao {
    @Query("SELECT * FROM cache_entries WHERE `key` = :key LIMIT 1")
    suspend fun get(key: String): CacheEntry?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(entry: CacheEntry): Long

    @Query("DELETE FROM cache_entries WHERE `key` = :key")
    suspend fun delete(key: String): Int

    @Query("DELETE FROM cache_entries")
    suspend fun clearAll(): Int

    @Query("SELECT COUNT(*) FROM cache_entries")
    suspend fun count(): Int

    @Query("SELECT * FROM cache_entries WHERE `key` LIKE :prefix || '%'")
    suspend fun getByPrefix(prefix: String): List<CacheEntry>

    @Query("DELETE FROM cache_entries WHERE ttlSeconds IS NOT NULL AND (updatedAt + ttlSeconds * 1000) < :nowMs")
    suspend fun clearExpired(nowMs: Long = System.currentTimeMillis()): Int
}